package com.lemon.components.baidu.voice;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import com.baidu.aip.util.Util;
import com.lemon.components.baidu.BaiduBase;

import javazoom.jl.player.Player;

public class BaiduVoice extends BaiduBase{
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	public void speek(String text){
    	// 初始化一个AipSpeech
        AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);


        HashMap<String, Object> options = new HashMap<String, Object>();
        options.put("spd", "6");
        options.put("pit", "5");
        //发音人选择, 0为女声，1为男声，3为情感合成-度逍遥，4为情感合成-度丫丫，默认为普通女
        options.put("per", "0");
        logger.debug("朗读内容：{}",text);
        // 调用接口
        TtsResponse res = client.synthesis(text, "zh", 1, options);
        byte[] data = res.getData();
        JSONObject res1 = res.getResult();
        if (data != null) {
            try {
                Util.writeBytesToFileSystem(data, "F:/tmp.mp3");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
        	if (res1 != null) {
        		System.out.println(res1.toString(2));
        	}
        	File tmp = new File("F:/tmp.mp3");
        	BufferedInputStream buffer = new BufferedInputStream(new FileInputStream(tmp));
        	Player player = new Player(buffer);
        	player.play();
        	tmp.delete();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}
